package com.mayflygeek.mayflyask.framework.webmvc.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;

import com.mayflygeek.mayflyask.framework.core.Idable;
import com.mayflygeek.mayflyask.framework.orm.BaseDao;
import com.mayflygeek.mayflyask.framework.orm.Query;
import com.mayflygeek.mayflyask.framework.util.Generics;
import com.mayflygeek.mayflyask.framework.webmvc.util.SearchUtil;

/**
 * @author 虫虫
 * @team 蜉蝣极客
 * @link www.mayflygeek.com
 * @Emial chongchong@mayflygeek.com
 * 
 */
public abstract class CrudController<T extends Idable<Long>> extends BaseController {
	public static final String DEFAULT_VARNAME = "entity";
	private Class<T> _entityClass;

	/**
	 * 获取对应dao
	 * 
	 * @return
	 */
	protected abstract BaseDao<T, Long> getBaseDao();

	protected Object doList(HttpServletRequest request, ModelMap model) {
		return list(request);
	}

	/**
	 * 获取查询结果
	 * 
	 * @param request
	 * @return
	 */
	protected Object list(HttpServletRequest request) {
		return getQuery(request).page();
	}

	protected Query<T, T> getQuery(HttpServletRequest request) {
		return SearchUtil.buildQuery(request, getBaseDao().query());
	}

	protected void doCreate(T entity, ModelMap model) {
		doCreate(entity);
	}

	protected void doCreate(T entity) {
		getBaseDao().save(entity);
	}

	protected void doUpdate(T entity, ModelMap model) {
		doUpdate(entity);
	}

	protected void doUpdate(T entity) {
		getBaseDao().update(entity);
	}

	protected void doDelete(T entity, ModelMap model) {
		doDelete(entity);
	}

	protected void doDelete(T entity) {
		getBaseDao().delete(entity);
	}

	/**
	 * 实体名（首字母小写）
	 * 
	 * @return
	 */
	protected final String entityName() {
		return classSimpleName(entityClass());
	}

	protected final String classSimpleName(Class<?> clazz) {
		Assert.notNull(clazz);

		final String classSimpleName = clazz.getSimpleName();
		return StringUtils.uncapitalize(classSimpleName);
	}

	@SuppressWarnings("unchecked")
	protected final Class<T> entityClass() {
		if (_entityClass == null) {
			if (getBaseDao() != null) {
				_entityClass = getBaseDao().getEntityClass();
			} else {
				_entityClass = (Class<T>) Generics.getTypeParameterClass(this.getClass());
			}
		}
		return _entityClass;
	}

	/**
	 * 实体对象在model中的命名.
	 * 
	 * @return
	 */
	protected String varName() {
		return DEFAULT_VARNAME; // 默认 "entity"
	}
}
